<template>
  <div>
    <el-form :inline="true" :model="searchForm" width="30%">
      <el-form-item label="教师名">
        <el-input v-model="searchForm.teacherName" placeholder="请输入教师名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="success" @click="showAddDialog">新增教师</el-button>
    <el-button type="info" @click="refreshTeachers">刷新教师</el-button>
    <el-table :data="teachers" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="teacherId" label="教师ID" width="100"></el-table-column>
      <el-table-column prop="teacherName" label="教师名称"></el-table-column>
      <el-table-column prop="workNum" label="工号"></el-table-column>
      <el-table-column prop="sex" label="性别"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="education" label="学历"></el-table-column>
      <el-table-column prop="eduSchool" label="毕业学校"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="380">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="confirmDeleteTeacher(scope.row.teacherId, scope.row.teacherName)">删除</el-button>
          <el-button size="mini" @click="showClassDialog(scope.row)">选择课程</el-button>
          <el-button size="mini" @click="showCourses(scope.row)">查看课程</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog title="添加教师" v-model="addVisible" width="30%">
      <el-form :model="addForm">
        <el-form-item label="教师名称" label-width="100px">
          <el-input v-model="addForm.teacherName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="教师工号" label-width="100px">
          <el-input v-model="addForm.workNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="100px">
          <el-input v-model="addForm.sex" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" label-width="100px">
          <el-input v-model="addForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" label-width="100px">
          <el-input v-model="addForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学历" label-width="100px">
          <el-input v-model="addForm.education" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="毕业学校" label-width="100px">
          <el-input v-model="addForm.eduSchool" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="addForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="addTeacher">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加和编辑教师的对话框 -->
    <el-dialog title="编辑教师" v-model="editVisible" width="30%">
      <el-form :model="editForm">
        <el-form-item label="教师名称" label-width="100px">
          <el-input v-model="editForm.teacherName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="教师工号" label-width="100px">
          <el-input v-model="editForm.workNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="100px">
          <el-input v-model="editForm.sex" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" label-width="100px">
          <el-input v-model="editForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" label-width="100px">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学历" label-width="100px">
          <el-input v-model="editForm.education" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="毕业学校" label-width="100px">
          <el-input v-model="editForm.eduSchool" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="updateTeacher">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看教师课程的对话框 -->
    <el-dialog title="教师课程" v-model="coursesDialogVisible" width="50%">
      <el-table :data="courses" style="width: 100%">
        <el-table-column prop="courseId" label="课程ID" width="100"></el-table-column>
        <el-table-column prop="courseName" label="课程名称"></el-table-column>
        <el-table-column prop="courseCredit" label="学分"></el-table-column>
        <el-table-column prop="courseTime" label="学时"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="mini" type="danger" @click="DeleteClass(scope.row.courseId, scope.row.courseName)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="coursesDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="选择课程" v-model="classDialogVisible" width="50%">
      <el-table :data="classes" style="width: 100%" @selection-change="handleClassSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="courseId" label="课程ID" width="100"></el-table-column>
        <el-table-column prop="courseName" label="课程名称"></el-table-column>
        <el-table-column prop="courseCredit" label="学分"></el-table-column>
        <el-table-column prop="courseTime" label="学时"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="classDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enrollSelectedClass">确认添加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {ElMessageBox} from "element-plus";

export default {
  name: 'TeacherList',
  data() {
    return {
      teachers: [],
      searchForm: {
        teacherName: ''
      },
      addVisible: false,
      editVisible: false,
      coursesDialogVisible: false,
      classDialogVisible: false,
      editForm: {
        teacherId: null,
        teacherName: '',
        workNum: '',
        sex: '',
        age: '',
        phone: '',
        education: '',
        eduSchool: '',
        remark: ''
      },
      addForm: {
        teacherId: null,
        teacherName: '',
        workNum: '',
        sex: '',
        age: '',
        phone: '',
        education: '',
        eduSchool: '',
        remark: ''
      },
      classes: [],
      courses: [], // 存储教师的课程数据
      selectedClasses: []
    };
  },
  methods: {
    fetchTeachers(params = {}) {
      axios.get(`${process.env.VUE_APP_API_BASE_URL}/teachers/list`, { params })
        .then(response => {
          this.teachers = response.data;
        })
        .catch(error => {
          console.error('Failed to fetch teachers:', error);
        });
    },
    async addTeacher() {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/teachers/add`, this.addForm);
        this.teachers.push(response.data); // 假设返回的新学生对象
        this.addVisible = false;
        this.resetAddForm();
        this.refreshTeachers();
      } catch (error) {
        console.error('Failed to add student:', error);
      }
    },
    resetAddForm() {
      this.addForm.teacherName = '';
      this.addForm.workNum = '';
      this.addForm.sex = '';
      this.addForm.age = '';
      this.addForm.phone = '';
      this.addForm.education = '';
      this.addForm.eduSchool = '';
      this.addForm.remark = '';
    },
    onSearch() {
      this.fetchTeachers({ teacherName: this.searchForm.teacherName });
    },
    resetForm() {
      this.searchForm.teacherName = '';
      this.fetchTeachers();
    },
    refreshTeachers() {
      this.fetchTeachers();
    },
    showAddDialog() {
      this.addForm = { teacherName: '',
        workNum: '',
        sex: '',
        age: '',
        phone: '',
        education: '',
        eduSchool: '',
        remark: '' };
      this.addVisible = true;
    },
    showClassDialog(classInfo) {
      this.currentClass = classInfo;
      this.fetchClass();
      this.classDialogVisible = true;
    },
    showEditDialog(row) {
      this.editForm = { ...row };
      this.editVisible = true;
    },
    handleClassSelectionChange(selection) {
      this.selectedClasses = selection;
    },
    async updateTeacher() {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/teachers/edit`, this.editForm);
        this.teachers.push(response.data); // 假设返回的新学生对象
        this.editVisible = false;
        this.refreshTeachers();
      } catch (error) {
        console.error('Failed to add student:', error);
      }
    },
    confirmDeleteTeacher(teacherId, teacherName) {
      this.$confirm(`确定要删除教师 "${teacherName}" 吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`${process.env.VUE_APP_API_BASE_URL}/teachers/delete/${teacherId}`)
          .then(() => {
            this.refreshTeachers();
          })
          .catch(error => {
            console.error('Failed to delete teacher:', error);
          });
      }).catch(() => {
        // 用户取消删除
      });
    },
    showCourses(teachers) {
      this.fetchEnrolledCourse(teachers.teacherId);
      this.coursesDialogVisible = true;
    },
    async fetchEnrolledCourse(teacherId) {
      try{
        const response =await axios.get(`${process.env.VUE_APP_API_BASE_URL}/teachers/enrolledCourse/${teacherId}`)
        this.courses = response.data;
        this.coursesDialogVisible = true;
      }catch(error) {
        console.error('Failed to fetch enrolled students:', error);
        this.$message({
          message: '获取已选学生失败',
          type: 'error'
        });
      }
    },
    DeleteClass(courseId, courseName) {
      ElMessageBox.confirm(
          `确定要删除课程 "${courseName}" 吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        this.deleteClass(courseId);
      }).catch(() => {
        // 用户取消删除
      });
    },
    async fetchClass() {
      try {
        const response = await axios.get(`${process.env.VUE_APP_API_BASE_URL}/courses/list`);
        this.classes = response.data;
      } catch (error) {
        console.error('Failed to fetch students:', error);
      }
    },
    async enrollSelectedClass() {
      if (this.selectedClasses.length === 0) {
        this.$message({
          message: '请选择至少一门课程',
          type: 'warning'
        });
        return;
      }
      const courseIds = this.selectedClasses.map(classes => classes.courseId);
      const data = {
        courseIds: courseIds,
        teacherId: this.currentClass.teacherId
      };
      try {
        await axios.post(`${process.env.VUE_APP_API_BASE_URL}/teachers/enrollClass`, data);
        this.$message({
          message: '教师成功添加这门课程',
          type: 'success'
        });
        this.classDialogVisible = false;
      } catch (error) {
        console.error('Failed to enroll students:', error);
        this.$message({
          message: '添加失败',
          type: 'error'
        });
      }
    },
    async deleteClass(courseId) {
      // 发送 DELETE 请求来删除学生
      try {
        await axios.delete(`${process.env.VUE_APP_API_BASE_URL}/teachers/deleteTea/${courseId}`);
        this.classes = this.classes.filter(classes1 => classes1.courseId !== courseId);
        this.coursesDialogVisible = false;
      } catch (error) {
        console.error('Failed to delete student:', error);
      }
    }
  },
  mounted() {
    this.fetchTeachers(); // 页面加载时立即获取教师列表
  }
};
</script>

<style scoped>
.el-select {
  width: 100%; /* 确保下拉框宽度足够 */
}
</style> 